﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;
using OntologyCache;

namespace biolit_config
{
    public partial class DownLoadProgress : Form
    {

        private List<OntList> downloads;
        Ontologies m_ontologies = new Ontologies();
        private int BackgroundState = 0;
        private string getStatus = null;
        private string size = null;
        public List<OntList> Downloads
        {
            get { return downloads; }
            set { downloads = value; }
        }
        
        public DownLoadProgress()
        {
            InitializeComponent();
        }

        private void DownLoadProgress_Load(object sender, EventArgs e)
        {
            dataGridView1.Columns.Add("OntologyName", "Ontology");
            dataGridView1.Columns.Add("Status", "Status");
            dataGridView1.Columns.Add("DateTime", "Time Stamp");
            dataGridView1.Columns.Add("DownloadSize", "Size");
            dataGridView1.Columns.Add("Error", "Error");
        }

        public void DoDownload()
        {
            
            List<OntList> ol = new List<OntList>();
            List<DownloadHistory> ontDownloadList = null;
            DateTime dtDownloadTime = System.DateTime.Now;
            string Status = null;
            string FileSize = null;
            string Error = null;
            if (Biolit_Settings.Settings != null)
            {
                ConfigSettings cs = Biolit_Settings.Settings;
                if (cs.DownloadedOntologies != null)
                    ontDownloadList = cs.DownloadedOntologies.ToList();
            }

            MakeOntologyIDLatest();
            string[] ontologyFiles = Directory.GetFiles(Biolit_Settings.Settings.OBO_DWNLDS);
            foreach (OntList ont in downloads)
            {
                bool fileExists = false;
                this.label1.Text = "Now downloading " + ont.Name;
                getStatus = null;
                Thread t = new Thread(this.BackGroundDownload);
                t.Start(ont);
                object[] rs = new object[] { ont.Name, "In Progress" };
                dataGridView1.Rows.Add(rs);

                while (t.IsAlive == true)
                {
                    Application.DoEvents();
                }
                if (ontologyFiles.Count() > 0)
                {
                    foreach (string filename in ontologyFiles)
                    {
                        int position = filename.LastIndexOf('\\');
                        if (position != -1)
                        {
                            string ontFileName = filename.Substring(position + 1);
                            string ontologyName = ontFileName.Remove(ontFileName.LastIndexOf('.'));
                            if (ontologyName.Equals(ont.Name, StringComparison.CurrentCultureIgnoreCase))
                            {
                                fileExists = true;
                                break;
                            }
                        }
                    }
                }
                    if (!fileExists)
                    {
                    if (dataGridView1.Rows.Count > 0)
                    {
                        int dataRow = dataGridView1.Rows.GetLastRow(DataGridViewElementStates.Displayed);
                        if (dataRow >= 0)
                        {
                            dtDownloadTime = System.DateTime.Now;
                            dataGridView1.Rows[dataRow].Cells[2].Value = dtDownloadTime;
                            if (size != null)
                                FileSize = size;
                            else
                                FileSize = "0 Bytes";
                            dataGridView1.Rows[dataRow].Cells[3].Value = FileSize;
                            if (getStatus == null)
                            {
                                Status = "Success";
                                dataGridView1.Rows[dataRow].Cells[1].Value = Status;
                            }
                            else
                            {
                                OntList ontologyList = new OntList(ont.Name, ont.ID, ont.Version, ont.Format, "Rest WebServices");
                                ol.Add(ontologyList);
                                Status = "Failed";
                                Error = getStatus.ToString();
                                dataGridView1.Rows[dataRow].Cells[1].Value = Status;
                                dataGridView1.Rows[dataRow].Cells[4].Value = Error;
                                dataGridView1.Rows[dataRow].Cells[3].Value = "";
                            }
                        }

                    }
                    }
                if (ontDownloadList == null)
                    ontDownloadList = new List<DownloadHistory>();
                if (ontDownloadList != null && ontDownloadList.Count > 0)
                {
                    if (false == DownloadItemExists(ontDownloadList, ont.Name))
                    {
                        ontDownloadList.Add(new DownloadHistory(ont.ID, ont.Name,ont.Version, ont.Format, Status, Convert.ToString(dtDownloadTime), FileSize, Error, "Rest WebServices"));
                    }
                }
                else if(ontDownloadList != null && ontDownloadList.Count == 0)
                    ontDownloadList.Add(new DownloadHistory(ont.ID, ont.Name,ont.Version, ont.Format, Status, Convert.ToString(dtDownloadTime), FileSize, Error, "Rest WebServices"));
                
                FileSize = null;
                Status = null;
                Error = null;
                
            }

            ConfigSettings configSettings = Biolit_Settings.Settings;
            if (configSettings.failedOnt != null && ol.Count > 0)
            {
                List<OntList> failedOntologyList = configSettings.failedOnt.ToList();
                foreach (OntList downloadOntList in ol)
                {
                    failedOntologyList.Add(downloadOntList);
                }
                configSettings.failedOnt = failedOntologyList.ToArray();
            }
            else
                Biolit_Settings.Settings.failedOnt = ol.ToArray();

            Biolit_Settings.Settings.DownloadedOntologies = ontDownloadList.ToArray();
            Biolit_Settings.StoreSettings();
            DataGridViewColumn dgv = dataGridView1.Columns[2];
            dataGridView1.Sort(dgv, ListSortDirection.Descending);
            progressBar1.Style = ProgressBarStyle.Blocks;
            progressBar1.Value = 1000;
            button1.Enabled = true;
            this.label1.Text = "Download Complete";
            //this.Close();
        }

        private void MakeOntologyIDLatest()
        {
            Dictionary<string, string> ontdict = m_ontologies.GetOntologies();

            if (ontdict.Count > 0)
            {
                foreach (OntList ont in downloads)
                {
                    if(ontdict.ContainsKey(ont.Name) == true)
                        ont.ID = ontdict[ont.Name];
                }
            }
        }

        private void BackGroundDownload(object o)
        {
            OntList ont = (OntList)o;
            if (ont.DownloadURL.Length > 0)
            {
                string dwnldPath = Biolit_Settings.Settings.OBO_DWNLDS;
                m_ontologies.DownloadOntology(ont, dwnldPath, ref getStatus, ref size);
            }
            // ok time to get the taglookup and tree data structures pre computed            
            MakeSmartTags(ont.Name, ont.Format);
        }

        private void MakeSmartTags(string ont_Name, string ont_Format)
        {
            string FileName = string.Empty;
            string oboFilName = Path.Combine( Biolit_Settings.Settings.OBO_DWNLDS ,ont_Name + "." + ont_Format.ToLower());
            if (!ont_Format.ToLower().Equals("owl"))
            {
                FileName = Path.Combine(Biolit_Settings.Settings.OBO_DWNLDS, ont_Name + ".dat");
                CacheManager.CreateNewPersistentCache(oboFilName, FileName, ont_Name);
            }
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private bool DownloadItemExists(List<DownloadHistory> ontList, string ontologyName)
        {
            Boolean alreadyInSelectedList = false;
            if (ontList != null && ontList.Count > 0)
            {
                foreach (DownloadHistory onlist in ontList)
                {
                    if (onlist._OntologyName.Equals(ontologyName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        alreadyInSelectedList = true;
                        break;
                    }
                }
            }
            return alreadyInSelectedList;
        }
    }
    }


